package com.example.goandroiddemo.http;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;

import com.chouren.goandroid.http.client.ApacheHttpClient;
import com.chouren.goandroid.http.client.HttpClient;
import com.chouren.goandroid.http.comm.KeyValuePair;
import com.chouren.goandroid.http.exception.HttpException;
import com.chouren.goandroid.http.parser.BitmapParser;
import com.chouren.goandroid.http.request.Request;
import com.chouren.goandroid.http.response.HttpStatus;
import com.chouren.goandroid.http.response.Response;
import com.chouren.goandroid.http.response.handler.HttpResponseHandler;
import com.chouren.goandroid.util.Logger;
import com.example.goandroiddemo.R;

public class HttpBitmapLoadTest extends Activity {
	private ImageView mImage;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bitmap_test);
		
		mImage = (ImageView)findViewById(R.id.imageView1);
		loadTest();
		
	}
	
	private void addImageView(Bitmap bitmap) {
		mImage.setImageBitmap(bitmap);
	}
	
	private void loadTest(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				testLoadImage();
			}
		}).start();
	}
	
	
	private void testLoadImage() {
		String imageUrl = "http://pic.yesky.com/imagelist/07/37/5146451_2754_1000x500.jpg";
		HttpClient httpClient = ApacheHttpClient.getInstance(this, 10000, false);
		final Response res = httpClient.execute(new Request(imageUrl)
			.setDataParser(new BitmapParser()
			.setBitmapSize(76, 76)));
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				new HttpResponseHandler() {
					@Override
					public void onSuccess(Response response, HttpStatus status, KeyValuePair[] headers) {
						Bitmap bitmap = response.getBitmap();
						Logger.debug(null, "bitmap:" + bitmap);
						addImageView(bitmap);
					}

					@Override
					public void onFailure(Response response, HttpException exception) {
						Toast.makeText(HttpBitmapLoadTest.this, "加载图片失败", Toast.LENGTH_SHORT).show();
					}
				}.handleResponse(res);
			}
		});
	}
}
